import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
// 引入组件
// import login from '../pages/login/login.vue'
// import index from '../pages/index/index.vue'
// import list from '../pages/list/list.vue'
// import detail from '../pages/detail/detail.vue'
// import search from '../pages/search/search.vue'
// import register from '../pages/register/register.vue'

// // 二级路由
// import home from "../pages/home/home.vue"
// import cate from "../pages/cate/cate.vue"
// import shop from "../pages/shop/shop.vue"
// import mine from "../pages/mine/mine.vue"
// 懒加载引入组件
//  let login=()=>import ('../pages/login/login.vue')
 let index=()=>import ('../pages/index/index.vue')
 let list=()=>import ('../pages/list/list.vue')
 let detail=()=>import ('../pages/detail/detail.vue')
 let search=()=>import ('../pages/search/search.vue')
 let register=()=>import ('../pages/register/register.vue')

 let home=()=>import ('../pages/home/home.vue')
 let cate=()=>import ('../pages/cate/cate.vue')
 let shop=()=>import ('../pages/shop/shop.vue')
 let mine=()=>import ('../pages/mine/mine.vue')


const routes = [
  {
    path: '/login',
    component: ()=>import ('../pages/login/login.vue'),//懒加载的另一种写法
    meta: {
      title: '登录'
    }
  },
  {
    path: '/index',
    component: index,
    children: [
      {
        path: 'home',
        component: home,
        meta: {
          title: '首页'
        }
      },
      {
        path: 'cate',
        component: cate,
        meta: {
          title: '分类'
        }
      },
      {
        path: 'shop',
        component: shop,
        meta: {
          title: '购物车'
        }
      },
      {
        path: 'mine',
        component: mine,
        meta: {
          title: '个人中心'
        }
      },
      // 二级重定向
      {
        path: '',
        redirect: 'home'
      }
    ]
  },
  {
    path: '/list',
    component: list,
    meta: {
      title: '商品列表'
    },
  },
  {
    path: '/detail/:id',
    component: detail,
    meta: {
      title: '商品详情'
    },
    // 只有打野才能访问详情页在此处加独享守卫
    // beforeEnter(to, from, next) {
    //   let type = localStorage.getItem("type")
    //   if (type == '2') {
    //     next()
    //   } else {
    //     next("/index/mine")
    //   }
    // }
  },
  {
    path: '/search',
    component: search,
    meta: {
      title: '商品搜索'
    },
    // 别名
    alias: '/s'
  },
  {
    path: '/register',
    component: register,
    meta: {
      title: '注册'
    }
  },
  {
    path: '*',
    redirect: '/login'
  }
]

const router = new VueRouter({
  // mode:"hash",//路由模式 默认hash 有#
  // mode:"history",//路由模式  history 无#
  routes
})

/* ------全局路由守卫------ */
router.beforeEach((to, from, next) => {
  if (to.path == '/login' || to.path == '/register') {
    next();
    return;
  }
  // 取出登陆时存的本地存储用来判断是否登录了
  let isLogin = localStorage.getItem('isLogin');
  if (isLogin) {
    next();
    return;
  }
  // 没有登录，直接跳转到登录页
  next('/login')
})

export default router
